/**
 * 过滤掉html
 * @param {*} html
 */
function get_text_purely(html) {
  if (!html) return html;
  const m = html.replace(/<[^>]+>/g, "");
  return m ? m : html;
}

/**
 * 过滤掉html，计算文本长度
 * @param {*} html
 */
function get_text_length_purely(html) {
  if (!html) return 0;
  var purely = get_text_purely();

  return purely ? purely.length : html.length;
}

/**
 * html去掉最外层的p标签
 * @param {*} html
 */
function get_html_without_tag_p(html) {
  const result = /<p.*>(.*?)(<\/p>)/gi.exec(html);
  if (!result && result.length < 2) return html;
  return result[1];
}

/**
 * 给行添加p标签
 * @param {*} lines
 */
function add_tag_p(lines) {
  for (let index = 0; index < lines.length; index++) {
    lines[index] = `<p>${lines[index]}</p>`;
  }
}

/**
 * 获取html中的表情图
 * @param {*} html
 * @returns {Object} html是处理后的html dict是图片缓存字典 用于后面还原
 */
function get_emotions_in_html(html) {
  let result = [];
  if (!html) return { html: html, dict: result };
  let limit = 1000; // 保险只处理1000
  while (limit >= 0) {
    var found = /(<img.*?>)/gi.exec(html);
    if (!found) break; // 遍历完成 退出循环
    const emotion = found[1];
    result.push({ index: found.index, emotion });
    html = html.replace(emotion, "");
    limit--;
  }
  return { html: html, dict: result };
}
if (!String.prototype.splice) {
    /**
     * {JSDoc}
     *
     * The splice() method changes the content of a string by removing a range of
     * characters and/or adding new characters.
     *
     * @this {String}
     * @param {number} start Index at which to start changing the string.
     * @param {number} delCount An integer indicating the number of old chars to remove.
     * @param {string} newSubStr The String that is spliced in.
     * @return {string} A new string with the spliced substring.
     */
    String.prototype.splice = function(start, delCount, newSubStr) {
        return this.slice(0, start) + newSubStr + this.slice(start + Math.abs(delCount));
    };
}
/**
 * 还原表情到html
 * @param {*} data
 */
function restore_emotions(html, dict) {
  dict = dict.reverse(); // 需要倒叙
  for (let index = 0; index < dict.length; index++) {
    const emotion = dict[index];
    if (emotion.index > html.length) continue;
    html = html.splice(emotion.index, 0, emotion.emotion);
  }
  return html;
}

/**
 * 显示文章逻辑
 * @param {String} html 文章正文
 * @param {Object} options  参数
 * @param {bool} displayAll 显示全部和外部通信
 */
export default function(val, len, append, prepend) {
  const emotions = []; // 保持图片字典
  let str = `<p>${prepend ? prepend : ""}${val}</p>`; // 系统有过滤掉掉一对p标签
  // 全文长度不够长，则返回了
  if (get_text_length_purely(str) < len) return str;

  const data = get_emotions_in_html(str); // 提出标表情
  str = data.html; // str在下文中不要改变，否则不能还原字典中的表情

  const result = str.match(/<p>(.*?)(<\/p>)/gi);
  if (result === null) return val;
  let resultVals = []; // 临时存储文本
  let currentLen = 0; // 长度控制

  for (let index = 0; index < result.length; index++) {
    let spaceLen = len - currentLen; // 还可以放多少字节
    if (spaceLen <= 0) break; // 空间不够了，推出循环

    const match = result[index];
    const text_purely = match.replace(/<[^>]+>/g, "");

    if (spaceLen < text_purely.length) {
      // 剩余的空间不够这个段落的字全部塞下，所以截取
      const text = text_purely.substring(0, spaceLen);
      resultVals.push(`${text}`);
      currentLen += text_purely.length;
      break;
    }

    // 空间还够塞
    resultVals.push(get_html_without_tag_p(match));
    currentLen += text_purely.length;
  }

  // 添加到最后一个
  if (append) {
    let last = resultVals[resultVals.length - 1];
    resultVals[resultVals.length - 1] = last + append;
  }

  // 循环添加上段落
  add_tag_p(resultVals);
  var html = resultVals.join("");
  return restore_emotions(html, data.dict);
}
